﻿using System;
using ECommon.Wrap;

namespace ECommon
{
    /// <summary>
    /// 结果封装工具类
    /// </summary>
    public static partial class ResultTool
    {
        /// <summary>
        /// 安全封装结果
        /// </summary>
        /// <typeparam name="T">结果泛型</typeparam>
        /// <param name="process">需要进行的处理</param>
        /// <returns>最后的结果封装</returns>
        public static ExResult<T> SafeWrap<T>(Func<T> process)
        {
            try
            {
                return Wrap(process);
            }
            catch (Exception ex)
            {
                ExResult<T> result = new ExResult<T>();
                result.Ex = ex;
                result.Status = 101;
                result.Msg = ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 封装结果
        /// </summary>
        /// <typeparam name="T">结果泛型</typeparam>
        /// <param name="process">需要进行的处理</param>
        /// <returns>最后的结果封装</returns>
        public static ExResult<T> Wrap<T>(Func<T> process)
        {
            ExResult<T> result = new ExResult<T>();
            if (process == null)
            {
                result.Status = 210;
                result.Msg = "处理函数不可为空";
            }
            else
            {
                result.Data = process();
                result.Status = 10;
                result.Msg = "执行成功";
            }
            return result;
        }


        /// <summary>
        /// 安全封装结果
        /// </summary>
        /// <typeparam name="T">结果泛型</typeparam>
        /// <param name="process">需要进行的处理</param>
        /// <returns>最后的结果封装</returns>
        public static ExResult SafeWrap(Action process)
        {
            try
            {
                return Wrap(process);
            }
            catch (Exception ex)
            {
                ExResult result = new ExResult();
                result.Ex = ex;
                result.Status = 101;
                result.Msg = ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 封装结果
        /// </summary>
        /// <typeparam name="T">结果泛型</typeparam>
        /// <param name="process">需要进行的处理</param>
        /// <returns>最后的结果封装</returns>
        public static ExResult Wrap(Action process)
        {
            ExResult result = new ExResult();
            if (process == null)
            {
                result.Status = 210;
                result.Msg = "处理函数不可为空";
            }
            else
            {
                result.Status = 10;
                result.Msg = "执行成功";
            }
            return result;
        }
    }
}
